package com.wangsd.web.coupon.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangsd.web.coupon.entity.Company;
import com.wangsd.web.coupon.entity.Merchant;
import com.wangsd.web.coupon.entity.ServiceBusiness;
import com.wangsd.web.coupon.entity.Store;
import com.wangsd.web.coupon.mapper.StoreMapper;
import com.wangsd.web.coupon.service.CompanyService;
import com.wangsd.web.coupon.service.MerchantService;
import com.wangsd.web.coupon.service.ServiceBusinessService;
import com.wangsd.web.coupon.service.StoreService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator
 * @since 2019-09-10
 */
@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

    @Resource
    StoreMapper storeMapper;

    @Autowired
    MerchantService merchantService;

    @Autowired
    CompanyService companyService;

    @Autowired
    ServiceBusinessService serviceBusinessService;

    @Override
    public IPage<Store> selectPage(Integer pageNum, Integer pageSize, Store params, String code) {
        Page<Store> page = new Page<>(pageNum, pageSize);
        IPage<Store> resultIPage = storeMapper.selectListXml(page, params, code);
        return resultIPage;
    }

    @Override
    @Transactional
    public void addOrUpdate(Store params) {
        if (params.getId() != null) {
            storeMapper.updateById(params);
        } else {
            storeMapper.insert(params);

            //保留检索CODE
            Merchant merchant = merchantService.getById(params.getMerchantId());
            params.setCode(merchant.getCode() + "-" + params.getId());
            storeMapper.updateById(params);
        }
    }

    @Override
    public List<Store> selectByCouponId(String id) {
        return storeMapper.selectByCouponId(id);
    }

    @Override
    public List<Map> selectAllByUserCode(String code) {
        List<Map> resultList = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.likeRight("code", code);
        }
        List<Store> list = storeMapper.selectList(queryWrapper);
        for (Store store : list) {
            Map map = new HashMap();
            map.put("code", store.getCode());
            map.put("name", store.getName());
            map.put("id", store.getId());
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public Store selectOutShopIdRepeat(String outShopId, Long id) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_shop_id", outShopId);
        if (id != null) {
            queryWrapper.ne("id", id);
        }
        return storeMapper.selectOne(queryWrapper);
    }

    @Override
    public JSONArray selectTree(String ctrlType, String displayType, Integer type, String code) {
        List<ServiceBusiness> businessList = null;
        List<Company> companyList = null;
        List<Merchant> merchantList = null;
        List<Store> storeList = null;
        if (StringUtils.isNotBlank(code)) {
            if (type == 1) {
                /*角色是服务商查询层级*/
                businessList = serviceBusinessService.selectByCode(code);
                companyList = companyService.selectAllByCode(code);
                merchantList = merchantService.selectAllByCode(code);
                storeList = this.selectAllByCode(code);
            } else if (type == 2) {
                /*角色是商圈查询层级*/
                companyList = companyService.selectByCode(code);

                String agentCode = companyList.get(0).getCode();
                String queryBusinessCode = agentCode.substring(0, agentCode.lastIndexOf("-"));
                businessList = serviceBusinessService.selectByCode(queryBusinessCode);

                merchantList = merchantService.selectAllByCode(code);
                storeList = this.selectAllByCode(code);
            } else if (type == 3) {
                /*角色是商户查询层级*/
                merchantList = merchantService.selectByCode(code);

                String merchantCode = merchantList.get(0).getCode();
                String queryAgentCode = merchantCode.substring(0, merchantCode.lastIndexOf("-"));
                companyList = companyService.selectAllByCode(queryAgentCode);

                String agentCode = companyList.get(0).getCode();
                String queryBusinessCode = agentCode.substring(0, agentCode.lastIndexOf("-"));
                businessList = serviceBusinessService.selectByCode(queryBusinessCode);

                storeList = this.selectAllByCode(code);
            } else if (type == 4) {
                /*角色是门店查询层级*/
                storeList = this.selectByCode(code);

                String storeCode = storeList.get(0).getCode();
                String queryStoreCode = storeCode.substring(0, storeCode.lastIndexOf("-"));
                merchantList = merchantService.selectByCode(queryStoreCode);

                String merchantCode = merchantList.get(0).getCode();
                String queryAgentCode = merchantCode.substring(0, merchantCode.lastIndexOf("-"));
                companyList = companyService.selectByCode(queryAgentCode);

                String agentCode = companyList.get(0).getCode();
                String queryBusinessCode = agentCode.substring(0, agentCode.lastIndexOf("-"));
                businessList = serviceBusinessService.selectByCode(queryBusinessCode);
            }
        } else {
            /*超级管理员查询层级*/
            businessList = serviceBusinessService.list();
            companyList = companyService.list();
            merchantList = merchantService.list();
            storeList = storeMapper.selectList(new QueryWrapper<>());
        }
        return packageData(businessList, companyList, merchantList, storeList, ctrlType, displayType);
    }

    private JSONArray packageData(List<ServiceBusiness> businessList,
                                  List<Company> companyList,
                                  List<Merchant> merchantList,
                                  List<Store> storeList, String ctrlType, String displayType) {
        //Map<Long, List<ServiceBusiness>> businessCollect = businessList.stream().collect(Collectors.groupingBy(ServiceBusiness::getId));
        Map<Long, List<Company>> agentCollect = companyList.stream().collect(Collectors.groupingBy(Company::getBusinessServiceId));
        Map<Long, List<Merchant>> merchantCollect = merchantList.stream().collect(Collectors.groupingBy(Merchant::getCompanyId));
        Map<Long, List<Store>> storeCollect = storeList.stream().collect(Collectors.groupingBy(Store::getMerchantId));
        JSONArray businessArray = new JSONArray();
        if (businessList != null) {
            for (ServiceBusiness serviceBusiness : businessList) {
                JSONObject businessObject = new JSONObject();
                businessObject.put("title", serviceBusiness.getName());
                businessObject.put("key", serviceBusiness.getCode());
                businessObject.put("value", serviceBusiness.getCode());
                if (StringUtils.isNotBlank(ctrlType)) {
                    if (ctrlType.contains("1")) {
                        businessObject.put("disabled", true);
                    }
                }
                if (displayType.contains("2")) {
                    /*拼装代理商*/
                    JSONArray agentArray = new JSONArray();
                    List<Company> agents = agentCollect.get(serviceBusiness.getId());
                    if (agents != null) {
                        for (Company agent : agents) {
                            JSONObject agentObject = new JSONObject();
                            agentObject.put("title", agent.getName());
                            agentObject.put("key", agent.getCode());
                            agentObject.put("value", agent.getCode());
                            if (StringUtils.isNotBlank(ctrlType)) {
                                if (ctrlType.contains("2")) {
                                    agentObject.put("disabled", true);
                                }
                            }
                            if (displayType.contains("3")) {
                                JSONArray merchantArray = new JSONArray();
                                List<Merchant> merchants = merchantCollect.get(agent.getId());
                                if (merchants != null) {
                                    for (Merchant merchant : merchants) {
                                        JSONObject merchantObject = new JSONObject();
                                        merchantObject.put("title", merchant.getName());
                                        merchantObject.put("key", merchant.getCode());
                                        merchantObject.put("value", merchant.getCode());
                                        if (StringUtils.isNotBlank(ctrlType)) {
                                            if (ctrlType.contains("3")) {
                                                merchantObject.put("disabled", true);
                                            }
                                        }
                                        if (displayType.contains("4")) {
                                            JSONArray storeArray = new JSONArray();
                                            List<Store> stores = storeCollect.get(merchant.getId());
                                            if (stores != null) {
                                                for (Store store : stores) {
                                                    JSONObject storeObject = new JSONObject();
                                                    storeObject.put("title", store.getName());
                                                    storeObject.put("key", store.getCode());
                                                    storeObject.put("value", store.getCode());
                                                    if (StringUtils.isNotBlank(ctrlType)) {
                                                        if (ctrlType.contains("4")) {
                                                            storeObject.put("disabled", true);
                                                        }
                                                    }
                                                    storeArray.add(storeObject);
                                                }
                                            }
                                            merchantObject.put("children", storeArray);
                                        }
                                        merchantArray.add(merchantObject);
                                    }
                                }
                                agentObject.put("children", merchantArray);
                            }
                            agentArray.add(agentObject);
                        }
                    }
                    businessObject.put("children", agentArray);
                }
                businessArray.add(businessObject);
            }
        }

        return businessArray;
    }

    public List<Store> selectAllByCode(String code) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.likeRight("code", code);
        }
        queryWrapper.eq("deleted", "0");
        List<Store> list = storeMapper.selectList(queryWrapper);
        return list;
    }

    public List<Store> selectByCode(String code) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.eq("code", code);
        }
        queryWrapper.eq("deleted", "0");
        List<Store> list = storeMapper.selectList(queryWrapper);
        return list;
    }
}
